﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;
using CodeRobot.Utility;
using System.Windows.Forms;

namespace CodeRobot.DAL
{
    /// <summary>
    /// .net core处理请求类-精简版
    /// </summary>
    public class ControllersMiniHelper
    {

        /// <summary>
        /// 根据表名创建Controllers类
        /// </summary>
        /// <param name="strFilePath">保存路径</param>
        /// <param name="strProjectName">项目名</param>
        /// <param name="strTableName">表名</param>
        public static void CreateControllersClass(string strFilePath, string strProjectName, string strTableName, string strTableComment, string strDBName)
        {
            //读取版权信息
            CodeRobot.Utility.IniFile iniFile = new Utility.IniFile(Application.StartupPath + "\\config.ini");
            string strCompany = iniFile.GetString("COPYRIGHT", "COMPANY", "");
            string strAuthor = iniFile.GetString("COPYRIGHT", "AUTHOR", "");
            string strVersion = iniFile.GetString("COPYRIGHT", "VERSION", "");
            string strCode = iniFile.GetString("COPYRIGHT", "CODE", "");
            string strCreateDate = iniFile.GetString("BASE", "CREATE_DATE", "");

            string strTableNameUpper = CommonHelper.GetTableNameUpper(strTableName);

            string strPrimaryKey = CommonHelper.GetPrimaryKey(strTableName);//如：news_id

            string strAllColumnName = CommonHelper.GetAllColumnName(strTableName);
            string strAllColumnNameNotKey = CommonHelper.GetAllColumnNameNotKey(strTableName);

            string strClassName = CommonHelper.GetClassName(strTableName);//类名
            strClassName = CommonHelper.GetTableNameUpper(strClassName);
            string strTableNameSpec = CommonHelper.GetTableNameFirstLowerSecondUpper(strClassName);//如：newsTypes
            string strTableNameLower = strTableNameSpec.ToLower();//如：newstypes

            Directory.CreateDirectory(strFilePath);
            StreamWriter sw = new StreamWriter(strFilePath + "\\" + strClassName + "Controller.cs", false, Encoding.GetEncoding("utf-8"));
            sw.WriteLine("using System;");
            sw.WriteLine("using System.Linq;");
            sw.WriteLine("using System.Threading.Tasks;");
            sw.WriteLine("using Microsoft.AspNetCore.Mvc;");
            sw.WriteLine("using Microsoft.EntityFrameworkCore;");
            // sw.WriteLine("using System.Collections.Generic;");
            sw.WriteLine("using " + strProjectName + ".Manage.Data;");
            sw.WriteLine("using " + strProjectName + ".Models;");
            sw.WriteLine("using " + strProjectName + ".Utility.Helper;");
            // sw.WriteLine("using Microsoft.AspNetCore.Http;");
            sw.WriteLine("using Senparc.CO2NET.Extensions;");
            sw.WriteLine("using Microsoft.AspNetCore.Authorization;");
            sw.WriteLine("");
            sw.WriteLine("namespace " + strProjectName + ".Manage.Controllers");
            sw.WriteLine("{");
            sw.WriteLine("");
            sw.WriteLine("    /// <summary>");
            sw.WriteLine("    /// 版权所有: Copyright © " + DateTime.Now.Year.ToString() + " " + strCompany + ". 保留所有权利。");
            sw.WriteLine("    /// 内容摘要: " + strClassName + " 处理请求的类");
            sw.WriteLine("    /// 创建日期：" + Convert.ToDateTime(strCreateDate).ToString("yyyy年M月d日"));
            sw.WriteLine("    /// 更新日期：" + DateTime.Now.ToString("yyyy年M月d日"));
            sw.WriteLine("    /// 版    本：V" + strVersion + "." + strCode + " ");
            sw.WriteLine("    /// 作    者：" + strAuthor);
            sw.WriteLine("    /// </summary>");
            sw.WriteLine("    [Authorize]");
            sw.WriteLine("    public class " + strClassName + "Controller : BaseController<" + strClassName + "Controller>");
            sw.WriteLine("    {");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// " + strTableComment + " 实例化数据上下文");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"context\"></param>");
            sw.WriteLine("        public " + strClassName + "Controller(" + strProjectName + "ManageContext context) : base(context)");
            sw.WriteLine("        {");
            sw.WriteLine("");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 获取" + strTableComment + "数据");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <returns>返回" + strTableComment + "JSON数据集合</returns>");
            //sw.WriteLine("        // GET: " + strTableNameLower + "/select");
            sw.WriteLine("        public async Task<IActionResult> Select()");
            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            sw.WriteLine("                var list = await _context." + strTableName + ".OrderBy(t => t." + strPrimaryKey + ").ToListAsync();");
            sw.WriteLine("                AddLogs((int)ENUMHelper.LogType.Search, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.Select + \"\" + (int)ENUMHelper.InfoType.Info, \"查询" + strTableComment + "下拉填充,DATA=\" + list.ToJson());");
            sw.WriteLine("");
            sw.WriteLine("                return Json(new { code = 0, msg = \"success\", data = list });");
            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> Select\");");
            sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Select, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("    }");
            sw.WriteLine("}");
            sw.Close();

        }


        /// <summary>
        /// 获取更新字段
        /// </summary>
        /// <param name="strNewName"></param>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetUpdateItems(string strDBName, string strNewName, string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA='" + strDBName + "' AND TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释

                    string strValue = "                item." + strColumnName + " = " + strNewName + "." + strColumnName + ";\r\n";
                    strReturnValue += strValue;
                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索字段列表", "GetSearchItemList", false);
            }

            return strReturnValue;

        }


    }
}
